// pages/index/index.js
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';
import { clearUserLocalStorage, userRequest } from "../../../../utils/util";
const app = getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        show: false,/*默认切换账号关闭*/
        user: undefined,
        delivery_district: undefined,
        delivery_man_list: [],//全部账号信息
        current_delivery_man_id: 0,
        current_delivery_name: '',
        level: 0,
        waiting_delivery_count: 0,    //未发货订单数
        waiting_review_count: 0,
        in_delivery_count: 0, //今日配送数量
        delivered_count: 0,
        in_after_sales_order_count: 0, //正在售后中的订单数
        done_after_sales_order_count: 0, //已完成售后的订单数
        today_fee: 0,
        month_fee: 0,
        today_count: 0,
        month_count: 0,
        today_delivered_money: 0,
        month_delivered_money: 0,
        month_status: {
            order_count: 0,
            order_money: 0.0
        },
        month_new_status: {
            order_count: 0,
            order_money: 0.0
        },
        status: null

    },
    onLoad(options) {
        let now = (new Date().getTime()) / 1000;
        let expiration_time = wx.getStorageSync('expiration_time')
        let group = wx.getStorageSync('role')
        // 调用检查登录状态的函数
        console.log('session:', app.session)
        // wx.setStorageSync('viewDeliveryDate', new Date())
        let access_token = app.session.access_token
        let level = wx.getStorageSync('level')
        let current_delivery_man_id = app.session.current_delivery_man_id || 0
        let current_delivery_district_id = app.session.current_delivery_district_id || 0
        this.setData({
            access_token,
            current_delivery_man_id,
            current_delivery_district_id,
            level,

        })
        this.checkLoginStatus(now, expiration_time, group, level);
        this.get_dashboard()


    },
    checkLoginStatus(now, expiration_time, group, level) {
        console.log(level)
        console.log(level !== "1" && level !== "9")
        if (group !== '配送司机' || now > expiration_time) {
            let groupName = group.name !== '配送司机' ? '非配送司机角色！' : '已过登录有效期!'
            wx.showToast({
                title: groupName,
                icon: 'error',
                duration: 2000
            });
            app.session = {};
            clearUserLocalStorage();
            setTimeout(() => {
                wx.reLaunch({
                    url: '/pages/selectID/selectID',
                });
            }, 1000);
        }
    },
    async get_dashboard() {
        const { current_delivery_man_id, current_delivery_district_id, access_token } = this.data
        const header = {
            'Content-Type': 'application/json',
            "x-api-key": access_token
        };
        const data = {
            current_delivery_man_id,
            current_delivery_district_id
        };
        const url = app.globalData.API + '/delivery/index/dashboard';
        try {
            const response = await userRequest(url, 'POST', data, header);
            console.log(response)

            if (response.code === 200) {
                const {
                    in_after_sales_order_count,
                    waiting_delivery_count,
                    in_delivery_count,
                    waiting_review_count,
                    delivered_count,
                    today_delivered_money,
                    month_delivered_money,
                    today_count,
                    today_fee,
                    month_count,
                    month_fee,
                    month_status,
                    month_new_status,
                    delivery_man_list,
                    delivery_district_list
                } = response.data;
                const defaultList = [
                    { 'value': 0, 'delivery_district_id': 0, 'text': '全部' },
                    { 'value': 0, 'text': '全部区域' }
                ];
                const formattedDeliveryManList = delivery_man_list ? defaultList.slice(0, 1).concat(delivery_man_list) : [];
                const formattedDeliveryDistrictList = delivery_district_list ? defaultList.slice(1).concat(delivery_district_list) : [];
                app.session.delivery_man_list = formattedDeliveryManList;
                app.session.delivery_district_list = formattedDeliveryDistrictList;
                this.setData({
                    delivery_man_list: formattedDeliveryManList,
                    delivery_district_list: formattedDeliveryDistrictList,
                    waiting_delivery_count: waiting_delivery_count || 0,
                    waiting_review_count: waiting_review_count || 0,
                    in_delivery_count: in_delivery_count || 0,
                    in_after_sales_order_count,
                    delivered_count: delivered_count || 0,
                    today_count,
                    today_fee,
                    month_count,
                    month_fee,
                    today_delivered_money,
                    month_delivered_money,
                    month_status,
                    month_new_status
                });
                wx.setStorageSync('delivery_district_list', formattedDeliveryDistrictList);
                wx.setStorageSync('delivery_man_list', formattedDeliveryManList);
                wx.setStorageSync('current_delivery_man_id', current_delivery_man_id);
                wx.setStorageSync('current_delivery_district_id', current_delivery_district_id);
            } else {
                wx.showToast({
                    title: response.data.message,
                    icon: 'error',
                    duration: 2000
                });
            }

        } catch (error) {
            if (error.code === 0) {
                clearUserLocalStorage();
                wx.reLaunch({
                    url: "/pages/selectID/selectID"
                });
            }
        }

    },
    on_dropdown_change(e) {
        // const current_delivery_man_id = e.detail;
        console.log(e)
        const { detail: current_delivery_man_id } = e;
        let [current_delivery_name, current_delivery_district_id] = ['未知', 0];
        // let current_delivery_name = '未知'
        // let current_delivery_district_id = 0
        const delivery_man = this.data.delivery_man_list.find(d => d.value === current_delivery_man_id);
        console.log(delivery_man)
        if (delivery_man) {
            ({ text: current_delivery_name, delivery_district_id: current_delivery_district_id } = delivery_man);
            // current_delivery_name = delivery_man.text;
            // current_delivery_district_id = delivery_man.delivery_district_id

            console.log('----', current_delivery_district_id)
        }
        this.setData({
            current_delivery_man_id,
            current_delivery_name,
            current_delivery_district_id

        });
        wx.setStorageSync('current_delivery_man_id', current_delivery_man_id);
        wx.setStorageSync('current_delivery_name', current_delivery_name);
        wx.setStorageSync('current_delivery_district_id', current_delivery_district_id);
        this.get_dashboard();
        //this.reLoad()
    },


    /**
     * 生命周期函数--监听页面加载
     */


    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        console.log('ready----------')
        //this.location();
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        console.log('show----------')
        let view_delivery_man_id = wx.getStorageSync('view_delivery_man_id') || 0
        let view_driver_name = ''
        let view_delivery_district_id = 0
        if (view_delivery_man_id > 0) {
            view_driver_name = wx.getStorageSync('view_driver_name')
            view_delivery_district_id = wx.getStorageSync('view_delivery_district_id')
        }
        this.setData({
            view_delivery_man_id,
            view_driver_name,
            view_delivery_district_id
        })
        this.get_dashboard()
        //this.reLoad()


    },

    // reLoad() {
    //     this.orderselect()
    //     // this.bindingOrderCount()
    //     // this.relieveOrderCount()
    // },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        this.monitoring()
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        console.log('隐藏了')
        // this.monitoring()
    },
    /**
     * 查询司机已经绑定的订单数量
     */
    // bindingOrderCount() {
    //     let that = this
    //     let mall_id = app.globalData.mall_id;
    //     let url = app.globalData.URL
    //     let id = this.data.id
    //     let username = this.data.username


    //     let view_delivery_man_id = wx.getStorageSync('view_delivery_man_id') || 0
    //     let view_driver_name = ''
    //     let view_delivery_district_id = 0
    //     if (view_delivery_man_id > 0) {
    //         view_driver_name = wx.getStorageSync('view_driver_name')
    //         view_delivery_district_id = wx.getStorageSync('view_delivery_district_id')
    //     }

    //     wx.userRequest({
    //         url: url + '/deliver.OrderV2/queryBinDing',
    //         method: "GET",
    //         data: {
    //             mall_id,
    //             id,
    //             username,
    //             view_delivery_district_id,
    //             view_delivery_man_id,
    //             view_driver_name
    //         },
    //         success: res => {
    //             let orders = res.data.data.orders
    //             console.log(orders)
    //             if (!orders) {
    //                 that.setData({
    //                     bindOrdersCount: 0
    //                 })
    //             } else {
    //                 let view_orders = [];
    //                 for (let i = 0; i < orders.length; i++) {
    //                     let remark = orders[i]['buyer_remark']
    //                     console.log('remark:', remark)
    //                     if (typeof remark === 'string' && remark.length > 0) {
    //                         view_orders.push(orders[i])
    //                     }
    //                 }
    //                 console.log('view_orders:', view_orders)
    //                 that.setData({
    //                     bindOrdersCount: orders.length,
    //                     view_buyer_remark: view_orders.length > 0,
    //                     view_buyer_remark_orders: view_orders,

    //                 })
    //             }

    //         }
    //     })
    // },

    // queryOrder(e) {
    //     let id = e.currentTarget.dataset.id
    //     this.getViewOrderInfo(id)
    // },

    // getViewOrderInfo(marker_id) {
    //     let id = marker_id
    //     let url = app.globalData.URL
    //     let mall_id = app.globalData.mall_id //获取主商城id
    //     wx.userRequest({
    //         url: url + '/deliver.OrderV2/getViewOrderInfo',
    //         method: "GET",
    //         data: {
    //             id,
    //             mall_id
    //         },
    //         success(res) {
    //             // console.log(res)
    //             if (res.data.code === 0) {
    //                 let dataStr = JSON.stringify(res.data.data)
    //                 wx.navigateTo({
    //                     url: '/templates/deliver/pages/orderAll/orderAll',
    //                     success(res) {
    //                         res.eventChannel.emit('orderAll', dataStr)
    //                     }
    //                 })
    //             }
    //         }
    //     })
    // },
    /**
     * 查询司机待处理订单数量
     */
    // relieveOrderCount() {
    //     let that = this
    //     let mall_id = app.globalData.mall_id;
    //     let url = app.globalData.URL
    //     let id = this.data.id
    //     let name = this.data.username
    //     let view_delivery_man_id = wx.getStorageSync('view_delivery_man_id') || 0
    //     let view_driver_name = ''
    //     let view_delivery_district_id = 0
    //     if (view_delivery_man_id > 0) {
    //         view_driver_name = wx.getStorageSync('view_driver_name')
    //         view_delivery_district_id = wx.getStorageSync('view_delivery_district_id')
    //     }

    //     wx.userRequest({
    //         url: url + '/deliver.OrderV2/abnormalOrderAll',
    //         method: "GET",
    //         data: {
    //             mall_id,
    //             id,
    //             name
    //         },
    //         success: res => {
    //             let data = res.data.data
    //             //console.log(res)
    //             if (!data) {
    //                 that.setData({
    //                     relieveOrder: 0
    //                 })
    //             } else {
    //                 that.setData({
    //                     relieveOrder: data.length
    //                 })
    //             }

    //         }
    //     })
    // },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        console.log('onPullDownRefresh-----------')
        let that = this;
        // that.query_drivers()
        // 自定义加载图标
        Toast.loading({
            duration: 1000,
            message: '加载中...',
            forbidClick: true,
            loadingType: 'spinner',
        });


        //定时两秒结束
        setTimeout(function () {
            that.reLoad()
            wx.stopPullDownRefresh()
        }, 1000);


    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    //读取司机用户缓存中的数据
    // index() {
    //     let delivery_man = wx.getStorageSync('delivery_man');
    //     let view_delivery_district_id = wx.getStorageSync('view_delivery_district_id');
    //     let view_delivery_man_id = wx.getStorageSync('view_delivery_man_id');
    //     let view_driver_name = wx.getStorageSync('view_driver_name');

    //     this.setData({
    //         id: delivery_man.delivery_man_id, //司机id
    //         level: delivery_man.level,
    //         delivery_man_id: delivery_man.delivery_man_id,
    //         username: delivery_man.delivery_man_name, //司机姓名
    //         phone: delivery_man.phone, //司机手机号
    //         area: delivery_man.area, //司机区域
    //         status: delivery_man.status, //司机状态,
    //         view_delivery_district_id,
    //         view_delivery_man_id,
    //         view_driver_name,
    //     })
    // },

    // async query_drivers() {
    //     let mall_id = app.globalData.mall_id;
    //     let delivery_man = wx.getStorageSync('delivery_man');
    //     let user_id = delivery_man.delivery_man_id;
    //     let cipher = delivery_man.cipher

    //     let url = app.globalData.URL + '/deliver.Driver/queryDrivers?mall_id=' + mall_id
    //     url += '&user_id=' + user_id
    //     url += '&cipher=' + cipher

    //     try {
    //         const { data: res } = await userRequest(url, 'GET')
    //         if (res.data.length > 0) {
    //             const driver_list = res.data.map(driver => ({
    //                 text: driver.username,
    //                 value: driver.id,
    //                 delivery_district_id: driver.delivery_district_id
    //             }))
    //             const defaultDriver = [{
    //                 text: '选择查看司机',
    //                 value: 0
    //             }];

    //             const new_driver_list = defaultDriver.concat(driver_list)
    //             console.log('drivers:', driver_list)

    //             this.setData({
    //                 view_delivery_man_id: 0,
    //                 driver_list: new_driver_list
    //             })
    //             wx.setStorageSync('driver_list', new_driver_list)
    //         }



    //     } catch (error) {
    //         console.error('Request failed:', error);
    //         // Handle the error appropriately
    //     }
    // },

    //查询顶部订单数量
    // async orderselect() {

    //     let delivery_man = wx.getStorageSync('delivery_man')
    //     let mall_id = app.globalData.mall_id;
    //     let area = delivery_man.area;
    //     let delivery_district_id = 0
    //     let username = delivery_man.delivery_man_name;
    //     let delivery_man_id = delivery_man.delivery_man_id

    //     let view_delivery_man_id = wx.getStorageSync('view_delivery_man_id') || 0
    //     if (view_delivery_man_id > 0) {

    //         delivery_man_id = wx.getStorageSync('view_delivery_man_id')
    //         username = wx.getStorageSync('view_driver_name')
    //         delivery_district_id = wx.getStorageSync('view_delivery_district_id')
    //     }

    //     console.log('6666666', area, delivery_district_id, username, delivery_man_id)

    //     let url = app.globalData.URL + '/deliver.OrderV2/getOrderArea?mall_id=' + mall_id
    //     url += '&area=' + area
    //     url += '&delivery_district_id=' + delivery_district_id
    //     url += '&driver_name=' + username
    //     url += '&delivery_man_id=' + delivery_man_id

    //     //获取区域查询数据
    //     const {
    //         data: res
    //     } = await wx.p.request({
    //         url: url,
    //         method: "GET",
    //     })



    //     this.setData({
    //         notAfterSalesCount: res.data.notAfterSalesCount,
    //         notOrderCount: res.data.notOrderCount,
    //         outAfterSalesCount: res.data.outAfterSalesCount,
    //         outOrderCount: res.data.outOrderCount,

    //         today_fee: res.data.today_fee,
    //         month_fee: res.data.month_fee,
    //         today_count: res.data.today_count,
    //         month_count: res.data.month_count,
    //         refund_count: res.data.order_refunds.length

    //     })

    // },
    view_statistics() {
        // temp disable statistics data. the data is not useful
        wx.navigateTo({
            url: '/templates/deliver/pages/deliveryStatistics/deliveryStatistics',
            //   success: res=>{
            //       res.eventChannel.emit('orderAll',dataStr)
            //   }
        })
    },

    //进入小程序就获取位置变化 插入司机数据库
    location() {
        var id = this.data.id;
        var username = this.data.username;
        var phone = this.data.phone;
        wx.getLocation({
            type: 'gcj02',
            success(d) {
                wx.request({
                    url: app.globalData.URL + '/deliver.location/updateLocation',
                    method: 'POST',
                    data: {
                        mall_id: app.globalData.mall_id, //主商城id
                        id: id,
                        username: username,
                        phone: phone,
                        lat: d.latitude,
                        long: d.longitude
                    },
                    success(res) {
                        //console.log(res)
                        if (res.data.code === 0) {
                            //console.log(res.data.message)
                        }
                    }
                });

            },
            fail(res) {
                Toast('获取位置失败,允许获取位置信息~');
            }
        })
    },
    //手机扫一扫查看订单信息
    // scanCode: function () {
    //     var that = this;
    //     wx.scanCode({ //扫描API
    //         success(res) { //扫描成功
    //             let result = res.result;

    //             if (!result || !/^[0-9a-zA-Z]*$/g.test(result)) {
    //                 wx.showModal({
    //                     title: '温馨提示',
    //                     content: '请扫正确的订单号',
    //                     showCancel: false
    //                 });

    //                 return false;
    //             }
    //             wx.request({
    //                 url: app.globalData.URL + '/deliver.order/getByOrderNo?order_no=' + result,
    //                 method: 'GET',
    //                 success(res) {
    //                     if (res.data.code === 1) {
    //                         Toast(res.data.message);
    //                         return false;
    //                     } else if (res.data.code === 0) {
    //                         var order_id = res.data.data.id;
    //                         Toast(res.data.message);
    //                         //传递订单id到页面
    //                         wx.navigateTo({
    //                             url: '/templates/deliver/pages/sweep/sweep?order_id=' + order_id,
    //                         })
    //                     }

    //                 }
    //             })
    //             that.setData({
    //                 scanCodeMsg: res.result
    //             });
    //             wx.showToast({
    //                 title: '成功',
    //                 duration: 1000
    //             })
    //         },
    //         fail() {
    //             wx.showToast({
    //                 title: '扫码异常?',
    //                 icon: 'error',
    //                 duration: 2000
    //             })
    //         }
    //     })
    // },
    scanBinding: function () {
        const that = this

        wx.scanCode({   //扫描API接口
            success: res => {
                let order_no = res.result//获取订单号
                if (!order_no || !/^[0-9a-zA-Z]*$/g.test(order_no)) {
                    wx.showModal({
                        title: '提示',
                        content: '请扫正确的订单号...',
                        showCancel: false
                    });
                    return false
                }

                wx.request({
                    url: app.globalData.API + '/delivery/index/query-order',
                    header: {
                        'Content-Type': 'application/json',
                        "x-api-key": this.data.access_token,
                    },
                    method: "POST",
                    data: {
                        order_no,
                    },
                    success: (res) => {
                        if (res.data.code === 200) {
                            console.log('6666')
                            let response = res.data.data
                            if (response.status == 0) {
                                let response_text = JSON.stringify(response)
                                wx.navigateTo({
                                    url: '/templates/deliver/pages/previewScanOrder/previewScanOrder',
                                    success(res) {
                                        // 通过eventChannel向被打开页面传送数据
                                        res.eventChannel.emit('response', response_text)
                                    }
                                })
                            } else if (response.status == -1) {
                                wx.showModal({
                                    title: '温馨提示',
                                    content: response.message,
                                    showCancel: false
                                });

                            } else if (response.status == 1) {
                                wx.showToast({
                                    title: '该订单已绑定!',
                                    icon: 'error',
                                    duration: 2000
                                })
                            }
                        } else if (res.data.code === 0) {
                            wx.showToast({
                                title: '扫码失败,重新试下?',
                                icon: 'error',
                                duration: 2000
                            })
                            //clearUserLocalStorage()
                            //wx.reLaunch({
                            //    url: "/pages/selectID/selectID"
                            //})
                        }
                    }
                })
            },
            fail() {
                wx.showToast({
                    title: '扫码失败,重新试下?',
                    icon: 'error',
                    duration: 2000
                })
            }
        })
    },
    //根据司机id 和 司机姓名 查询已绑定订单 2025/2/27
    viewInDelivery() {
        wx.navigateTo({
            url: '/templates/deliver/pages/inDelivery/inDelivery',
            success: res => {
                res.eventChannel.emit('orderAll', dataStr)
            }
        })
    },
    // 2025/2/27
    viewWaitingReview() {
        wx.navigateTo({
            url: '/templates/deliver/pages/waitingReview/waitingReview',
            //   success: res=>{
            //       res.eventChannel.emit('orderAll',dataStr)
            //   }
        })
    },
    // 2025/2/27
    // viewInReturn() {
    //     wx.navigateTo({
    //         url: '/templates/deliver/pages/inReturn/inReturn',
    //         //   success: res=>{
    //         //       res.eventChannel.emit('orderAll',dataStr)
    //         //   }
    //     })
    // },
    // 2025/2/27
    // viewDelivered() {
    //     wx.setStorageSync('viewDeliveryDate', new Date())
    // 	},
    // 干货汇总单
    ghhzorder() {
        wx.navigateTo({
            url: '/templates/deliver/pages/goodsList/goodsList',
        })
    },
    // viewReturned() {
    //     wx.setStorageSync('viewDeliveryDate', new Date())
    //     wx.navigateTo({
    //         url: '/templates/deliver/pages/returned/returned',
    //     })

    // },

    logout() {
        Dialog.confirm({
            title: '账号退出',
            message: '您确定要退出当前账号？',
        })
            .then(() => {
                clearUserLocalStorage()
                setTimeout(() => {
                    wx.reLaunch({
                        url: '/pages/selectID/selectID',
                    })
                }, 1000)
            })
            .catch(() => {
                // 取消退出
                Toast('取消退出~');
            });
    },
    // 监测账号登录状态
    monitoring() {
        console.log('我在监控账号状态');
        let role = wx.getStorageSync("role");
        if (role !== '配送司机') {
            //wx.clearStorageSync();
            wx.reLaunch({
                url: "/pages/selectID/selectID"
            })
        }
    }
})